package net.touchcapture.qr.flutterqr

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.provider.MediaStore
import com.google.zxing.BinaryBitmap
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.*
import kotlin.concurrent.timerTask

object QrImgUtil {

    var curImgPath = ""
    var timer: Timer? = null
    var qrInfo = ""
    fun scanLastImg(mContext: Context, scanCallback: ResultCallBack) {
        Flowable.just(1).map {
            getLastPic(mContext)//获取最近图片子线程执行
        }.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())//主线程执行后续方法
                .flatMap {
                    Flowable.fromIterable(it)//列表操作
                }.toSortedList { o1, o2 ->
                    //排序
                    o2.first.compareTo(o1.first)
                }.map { listData ->
                    if (listData.size == 0) Pair("", "") else listData[0] //返回获取的数据
                }.observeOn(Schedulers.newThread()).map { finalData ->
                    finalData.second
                }.observeOn(Schedulers.newThread()).map {
                    var result = ""
                    if (it.isNotEmpty()) {
                        var bitMap = getBitMap(it)
                        bitMap?.run {
                            val pixels = IntArray(width * height);
                            getPixels(pixels, 0, width, 0, 0, width, height);
                            val source = RGBLuminanceSource(width, height, pixels);
                            val binaryBitmap = BinaryBitmap(HybridBinarizer(source));
                            val reader = QRCodeReader();
                            try {
                                reader.decode(binaryBitmap).text.run { //重复类型的数据不再识别发送
                                    if (this != qrInfo) {
                                        qrInfo = this
                                        result = this
                                    }
                                }
                            } catch (e: Exception) {
                            }
                            recycle()//回收图片
                        }
                        bitMap = null//图片置空
                    }
                    System.gc()//系统回收
                    result
                }.observeOn(AndroidSchedulers.mainThread()).subscribe { result ->
                    //主线执行返回结果
                    scanCallback.scanComplete(result)
                }
    }

    ///重置当前图片地址
    private fun resetImgPath() {
        curImgPath = ""
        qrInfo = ""
        timer?.cancel()
    }

    ///获取bitmap
    private fun getBitMap(path: String): Bitmap? {
        var second = 0
        curImgPath = path
        timer?.cancel()
        timer = Timer()
        timer?.schedule(timerTask {
            second += 1
            if (second == 120) {
                resetImgPath();
            }
        }, 0, 1000)
        val bitMap = BitmapFactory.decodeFile(path)
        return bitMap
    }

    ///获取数据库图片列表
    private fun getLastPic(mContext: Context): MutableList<Pair<String, String>> {
        val pathList = mutableListOf<Pair<String, String>>()
        val resolver = mContext.contentResolver //获取共享数据提供器
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI//设置Uri
        val cursor = resolver.query( //通过resolver获取游标访问数据库存储
                uri, null, null, null
                , MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC"
        )
        cursor?.run {
            while (moveToNext()) {
                val filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))//获取地址
                val addTime =
                        cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED))//获取添加事件
                if (dealDate(addTime) && filePath != curImgPath) {//时间小于两分钟，且路径不能与上一次检测的最后一张图片相同
                    pathList.add(Pair(addTime, filePath));
                }
            }
            cursor.close()//关闭游标
        }
        return pathList;
    }

    ///处理时间
    private fun dealDate(addTime: String) =
            ((System.currentTimeMillis()) - addTime.toLong() * 1000) < 2 * 60 * 1000


    ///扫描结果回调
    interface ResultCallBack {
        fun scanComplete(result: String)
    }
}

